﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;


namespace SilverlightUpload
{
    public partial class MainPage : UserControl
    {
        public class ProgressEventArgs:EventArgs
        {
            public ProgressEventArgs(double datasent)
            {
                Percent = datasent;
            }
            public double Percent { get; set; }
        }
        Dictionary<string, string> param;
        public MainPage(Dictionary<string, string> paramsDic)
        {
            InitializeComponent();

            param = paramsDic;
            txtbUserID.Text = param["DispName"];

            //if (DesignerProperties.GetIsInDesignMode(this))
            //    return;

            //OnProgressChange += new ProgressHandle(MainPage_OnProgressChange);
        }

        void MainPage_OnProgressChange(object sender, MainPage.ProgressEventArgs e)
        {
            ProgressBar.Value = e.Percent;
        }

        private WebClient client;
        public delegate void ProgressHandle(object sender, ProgressEventArgs e);

        public event ProgressHandle OnProgressChange;

        private long dataSent=0;

        private BackgroundWorker backgroundWorker;

        private long sentBytes = 0;
        private List<FileInfo> fileList;
        private List<PicItemBase> items
        {
            get { return picItems1.Items; }
        }
         private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog()
                {
                    Filter = "Jpeg Files (*.jpg)|*.jpg|All Files (*.*)|*.*",
                    Multiselect = true
                };

            if (true == dlg.ShowDialog())
            {
                fileList = new List<FileInfo>(dlg.Files);
                foreach (FileInfo fileInfo in fileList)
                {
                    picItems1.Add(fileInfo);
                    ProgressBar.Maximum = picItems1.TotalSize;
                }
            }
        }

        private void uploadData(Stream input, Stream output)
        {
            byte[] buffer = new byte[4096];
            int bytes;

            while ((bytes = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytes);
                dataSent += bytes;
                long l = dataSent * 100;
                output.Flush();
                //backgroundWorker.ReportProgress((int)(l / picItems1.TotalSize));
                //this.Dispatcher.BeginInvoke(delegate
                //                                {
                //                                    OnProgressChange(this, new ProgressEventArgs(dataSent));
                //                                });
                
                //System.Threading.Thread.Sleep(100);
            }
        }

        private void Upload_Click(object sender, RoutedEventArgs e)
        {
            btnLoadImages.IsEnabled = false;
            btnUpload.IsEnabled = false;
            waitIcon1.Visibility = System.Windows.Visibility.Visible;
            waitIcon1.Storyboard1.Begin();
            if (picItems1.Items.Count<=0)
            {
                MessageBox.Show("No Pic selected.");
                return;
            }
            Uri uri = new Uri(@"/UploadImages/DataHandler.ashx",UriKind.Relative);
            try
            {
                client = new WebClient();
            client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
            client.WriteStreamClosed += new WriteStreamClosedEventHandler(client_WriteStreamClosed);
            client.OpenWriteCompleted += delegate(object s, OpenWriteCompletedEventArgs ex)
                                             {
                                                 worker_DoWork(this, new DoWorkEventArgs(ex));
                                                 ex.Result.Flush();
                                                 ex.Result.Close();

                                             };
            
                client.OpenWriteAsync(uri);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        void client_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
        {
            waitIcon1.Visibility = Visibility.Collapsed;
            MessageBox.Show(e.Error == null ? "完成上传。" : string.Format("上传过程中发生错误！", e.Error.Message));
            btnUpload.IsEnabled = true;
            btnLoadImages.IsEnabled = true;
        }

        private void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            ProgressBar.Value = e.BytesReceived;
            picItems1.txtSumeray.Text = e.BytesReceived.ToString();
            
            this.Dispatcher.BeginInvoke(delegate
                                                {
                                                    OnProgressChange(this, new ProgressEventArgs(dataSent));
                                                });
        }

        //private void WriteCallback(IAsyncResult asynchronousResult)
        //{
        //        HttpWebRequest webrequest = (HttpWebRequest)asynchronousResult.AsyncState;
        //    // End the operation.
        //    Stream requestStream;
            
        //        requestStream = webrequest.EndGetRequestStream(asynchronousResult);

        //        using (BinaryWriter bw = new BinaryWriter(requestStream))
        //        {
        //            //backgroundWorker = (BackgroundWorker) sender;
        //            try
        //            {

        //                bw.Write(picItems1.Items.Count);
        //                foreach (PicItemBase item in picItems1.Items)
        //                {
        //                    WritePicInfo(bw, item);
        //                }
        //            }
        //            catch (Exception exception)
        //            {
        //                MessageBox.Show("上传错误。" + exception.Message);
        //            }
        //            //MessageBox.Show("上传完成");
        //        }
        //        // Start the asynchronous operation to get the response
        //        webrequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webrequest);
        //}

        //private static void GetResponseCallback(IAsyncResult asynchronousResult)
        //{
        //    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        //    // End the operation
        //    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        //    Stream streamResponse = response.GetResponseStream();
        //    StreamReader streamRead = new StreamReader(streamResponse);
        //    string responseString = streamRead.ReadToEnd();
        //    Console.WriteLine(responseString);
        //    // Close the stream object
        //    streamResponse.Close();
        //    streamRead.Close();

        //    // Release the HttpWebResponse
        //    response.Close();
        //    //allDone.Set();
        //}

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressBar.Value = e.ProgressPercentage;
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("File Upload complete.");
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
                {OpenWriteCompletedEventArgs ex = (OpenWriteCompletedEventArgs)e.Argument;
            using (BinaryWriter bw = new BinaryWriter(ex.Result))
            {
                //backgroundWorker = (BackgroundWorker) sender;
                

                    bw.Write(picItems1.Items.Count);
                    foreach (PicItemBase item in picItems1.Items)
                    {
                        WritePicInfo(bw, item);
                    }
                
                //MessageBox.Show("上传完成");
            }}
                catch (Exception exception)
                {
                    MessageBox.Show("上传错误。" + exception.Message);
                }
        }

        private void WritePicInfo(BinaryWriter bw, PicItemBase item)
        {

            byte[] desc = System.Text.Encoding.UTF8.GetBytes(item.Description);
            byte[] person = System.Text.Encoding.UTF8.GetBytes(item.Person);
            bw.Write(desc.Length);
            bw.Write(desc, 0, desc.Length);
            bw.Write(person.Length);
            bw.Write(person, 0, person.Length);
            bw.Write(BitConverter.GetBytes(item.TakeDate.ToOADate()));
            bw.Write(item.File.Length);
            sentBytes += item.File.Length;
            using (Stream stream=item.File.OpenRead())
            {
                uploadData(stream, bw.BaseStream);

                
                Dispatcher.BeginInvoke(delegate
                                           {
                                               //waitIcon1.txtUploadPercent.Text = string.Format("{0}%",
                                               //sentBytes*100/picItems1.TotalSize);
                                           });
            }
        }




    }
}
